import {
  C44InvoiceListItem,
  CheckBox,
  Layout,
  UserSubPageBase,
  C13BottomDock,
} from "@/components";
import { useEffect, useState } from "react";
import { useRouter } from "@tarojs/taro";
import { useAuth } from "@/store/authContext";
import { getInvoicableOrders } from "@/store/userDataContext";
import { InvoicableOrdersResponseShape } from "@/data/invoice/invoiceTypes";
import { View } from "@tarojs/components";
import { navigateTo } from "@/utils/navigation";
import { useApplicationInfo } from "@/store/applicationDataContext";
import style from "./index.module.scss";

export default function UserInvoiceSelect() {
  const { dispatchAuthAction } = useAuth();
  const [selectableOrders, setSelectableOrders] =
    useState<InvoicableOrdersResponseShape>([]);
  const [selectedForInvoice, setSelectedForInvoice] =
    useState<InvoicableOrdersResponseShape>([]);

  const { params } = useRouter();
  const { dispatch } = useApplicationInfo();

  // Only initialize once per view
  useEffect(() => {
    const misc = params.id
      ? {
          query: { orderNo: params.id },
          authDispatch: dispatchAuthAction,
        }
      : { authDispatch: dispatchAuthAction };
    const Initialize = async () => {
      const selectionResponse = await getInvoicableOrders(misc);
      setSelectableOrders(selectionResponse);

      // Referring to pre-selection if coming from other page
      if (params.id) {
        setSelectedForInvoice(
          selectionResponse.filter((res) => res.orderNo === params.id)
        );
      }
    };
    Initialize();
  }, []);

  return (
    <Layout>
      <UserSubPageBase title="开发票" subTitleParagraph="可开票订单" scrollable>
        <View className={style["invoice-select-wrapper"]}>
          {selectableOrders.map((order) => (
            <View key={order.orderNo} className={style["list-item-wrapper"]}>
              <CheckBox
                onChangeCb={(e) => {
                  const checked = !!e.detail.value.length;
                  setSelectedForInvoice((prevCheckedItemsList) => {
                    if (checked) {
                      return [...prevCheckedItemsList, order];
                    } else {
                      return prevCheckedItemsList.filter(
                        (val) => val.orderNo !== order.orderNo
                      );
                    }
                  });
                }}
                checked={selectedForInvoice.includes(order)}
                intiallyChecked={selectedForInvoice.includes(order)}
              />
              <C44InvoiceListItem
                orderNo={order.orderNo}
                payTime={order.payTime}
                name={order.name}
                payPrice={order.payPrice}
              />
            </View>
          ))}
        </View>
      </UserSubPageBase>
      <View className={style["dock-wrapper"]}>
        <C13BottomDock
          onPrimaryClick={{
            text: "下一步",
            cb: () => {
              dispatch({
                type: "SET_INVOICE_ORDER_NUMBERS",
                data: selectedForInvoice.map((order) => order.orderNo),
              });
              navigateTo("pages/user-invoice-form/index");
            },
            disabled: !selectedForInvoice.length,
          }}
          onSecondaryClick={null}
        />
      </View>
    </Layout>
  );
}
